package com.miao.config;

import com.miao.pojo.Configuration;
import com.miao.pojo.MappedStatement;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.InputStream;
import java.util.List;

/**
 * @author 喵瑞恒
 * @date 2023/09/13 21:11
 **/
public class XMLMapperBuilder {

    private Configuration configuration;

    public XMLMapperBuilder(Configuration configuration) {
        this.configuration = configuration;
    }

    public void parse(InputStream resourceAsStream) throws DocumentException {
        SAXReader saxReader = new SAXReader();
        Document document = saxReader.read(resourceAsStream);
        Element rootElement = document.getRootElement();

        /*<select id="selectOne" resultType="com.miao.pojo.User" parameterType="com.miao.pojo.User">
                select * from user where id=#{id} and username=#{username}
        </select>*/
        List<Element> selectList = rootElement.selectNodes("//select");
        String namespace = rootElement.attributeValue("namespace");


        for (Element element : selectList) {
            String id = element.attributeValue("id");
            String resultType = element.attributeValue("resultType");
            String parameterType = element.attributeValue("parameterType");
            String sql = element.getTextTrim();

            //封装mappedStatement对象
            MappedStatement mappedStatement = new MappedStatement();

            String statementId = namespace + "." + id;
            mappedStatement.setStatementId(statementId);
            mappedStatement.setResultType(resultType);
            mappedStatement.setParameterType(parameterType);
            mappedStatement.setSql(sql);
            mappedStatement.setSqlCommandType("select");

            //将封装好的mappedStatement对象封装到configuration中的map集合中
            configuration.getMappedStatementMap().put(statementId, mappedStatement);

        }


    }
}
